<style>
  .img { background: #fff; padding: 5px 5px 15px 5px; margin: 0 2px; border: 1px solid #666; display: inline-block; }
  .img img { cursor: pointer; }
</style>

<?php 
$id = Utils::get_param('id', 0);
$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$data = $orm->get('pb_ecom_hm_banner', NULL, NULL, NULL, NULL, $opts)->d;

$objs = $orm->get('pb_ecom_hm_banner', NULL, NULL, NULL, NULL, NULL)->d;
?>
<div class="pure-form pure-form-aligned" style="padding: 10px; width: 640px;">
  <legend>Banner</legend>

  <div class="pure-control-group">
    <label>URL</label>
    <input id="url" type="text" class="pure-input-1-2" style="width: 480px;" placeholder="{URL}" />
  </div>
  
  <div class="pure-control-group">
    <label>Icon (512k or less)<span  id="uploader"></span></label>
    <label style="text-align: left; height: 95px; vertical-align: middle;"><span id="icon">&nbsp;</span></label>
  </div>
  
  <div class="pure-control-group">
    <label>Text</label>
    <textarea id="txt" type="text" class="pure-input-1-2" placeholder="{Text}" style="resize: none; height: 100px;"></textarea>
  </div>
  
  <div class="pure-control-group">
    <label>&nbsp;</label>
    <button class="pure-button pure-input-1-2 pure-button-primary" onclick="submit_obj();">Save</button>
  </div>
  
  <div class="pure-control-group expg">
    <label>&nbsp;</label>
    <button class="pure-button" onclick="delete_obj();">Delete</button>
    <button class="pure-button" onclick="__data = []; reset(); render();">New Banner</button>
  </div>
</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __objs = JSON.parse('<?php echo addslashes(json_encode($objs)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __dir = '<?php echo PLGN_DIR . basename(dirname(__FILE__)); ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __session_id = '<?php echo session_id(); ?>';
  var __tmp = null;
  
  $(function() {
    reset();
    render();
    Upload.init(
      'uploader', 
      __requrl + 'upload_icon', 
      function(rslt, srv_err) {
        __data[0].file = rslt[0].file;
        render_file();
      }, 
      {
        file_queue_limit: 1,
        file_size_limit: '1MB',
        upload_start_handler: function(file) {
          this.setPostParams({
            PHPSESSID: __session_id,
            id: __data[0].id,
            file: __data[0].file
          });
        },
        debug: 0
      }
    );
  });
  
  function reset() {
    __objs = __objs.sort(function(a, b) {
      return parseFloat(a.order, 10) > parseFloat(b.order, 10);
    });
    __root = Utils.get_root(__objs);
    if (__data.length == 0) {
      __data[0] = {
        id: 0,
        order: 0,
        parent_id: 0,
        url: '',
        txt: '',
        file: ''
      };
    }
  };

  function __set_objs(node, elm) {
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      elm.append('<li value="' + itm.id +'">' +
                    '<a href="#"' + ((__data.length > 0 && __data[0].id == itm.id) ? ' class="jstree-clicked"' : '') + '>' + itm.txt + '</a>' +
                    ((itm.__c.length > 0) ? '<ul id="pgul_' + itm.id + '"></ul>' : '') + 
                 '</li>');
      if (itm.__c.length > 0) {
        __set_objs(itm, $('#pgul_' + itm.id));
      }
    }
  }

  function render() {
    if (__data[0].id != 0) {
      $('.expg').show();
    } else {
      $('.expg').hide();
    }
    $("#cs_leftbar_objs").empty();
    $("#cs_leftbar_objs").append('<h3 style="padding-left: 10px;">Banners</h3>');
    $("#cs_leftbar_objs").append('<div id="pgul_wrapper" style="padding: 10px 5px; background: #F5F5F5;"></div>');
    $('#pgul_wrapper').append('<ul id="pgul_' + __root.id + '"></ul>');
    __set_objs(__root, $('#pgul_' + __root.id));
    $("#pgul_wrapper")
    .jstree({ "plugins" : ["themes", "html_data", "ui"] })
    .on('loaded.jstree', function() {
      $("#pgul_wrapper").jstree('open_all');
    })
    .bind("select_node.jstree", function (event, data) { 
      var req = {
        id: data.rslt.obj.attr("value")
      };
      Ajax.request(
        __requrl + 'get_obj',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          __data = rslt;
          render_data();
        },
        null
      );
    })
    .delegate("a", "click", function (event, data) { event.preventDefault(); });
    render_data();
  };
  
  function render_data() {
    Url.insert_param('id', __data[0].id);
    $('#url').val(__data[0].url);
    $('#txt').val(__data[0].txt);
    render_file();
  };

  function render_file() {
    $('#icon').empty();
    if (__data[0].file != '') {
      $('#icon').append(
          '<table cellpadding=0 cellspacing=0 class="img">' +
            '<tr><td style="text-align: right;"><i class="fa fa-times" onclick="delete_file();"></i></td></tr>' +
            '<tr><td><a rel="prettyPhoto[gallery1]" href="' + __data[0].file + '"><img style="height: 40px;" src="' + __data[0].file + '"></img></a></td></tr>' +
          '</table>');
      $("a[rel^='prettyPhoto']").prettyPhoto({
        social_tools: ''
      });
    }
  };

  function submit_obj() {
    req = __data[0];
    req.url = $('#url').val();
    req.txt = $('#txt').val();
    if (req.id == 0) {
      req.__file = req.file;
    }
    
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        if (rslt.__objs) {
          __objs = rslt.__objs;
          delete rslt.__objs;
        }
        __data[0] = rslt;
        reset();
        render();
      },
      null
    );
  };
  
  function delete_obj() {
    Ajax.request(
      __requrl.replace(__file, 'index') + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(__data[0])),
      function(rslt) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id);
      },
      { confirm: 1 }
    );
  };

  function get_obj(id) {
    var req = {
      id: id
    };
    Ajax.request(
      __requrl + 'get_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        render();
      },
      null
    );
    return false;
  };

  function delete_file() {
    if (__data[0].id != 0) {
      __data[0].__nofile = 1;
      submit_obj();
    }
    __data[0].file = '';
    render_file();
  };
  /*]]>*/
</script>